<template>
  <div class="paypal-payment">
    <h2>生成 PayPal 支付单号</h2>
    <el-form @submit.prevent="createPayPalOrder" :model="formData" :rules="rules" ref="paypalForm">
      <el-form-item label="唯一标识" prop="uni">
        <el-input v-model="formData.uni" placeholder="请输入唯一标识"></el-input>
      </el-form-item>
      <el-form-item label="订单号" prop="orderNo">
        <el-input v-model="formData.orderNo" placeholder="请输入订单号"></el-input>
      </el-form-item>
      <el-form-item label="支付方式">
        <el-input v-model="formData.payType" disabled></el-input>
      </el-form-item>
      <el-form-item label="支付渠道">
        <el-input v-model="formData.payChannel" disabled></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit" :loading="loading">生成支付链接</el-button>
      </el-form-item>
    </el-form>

    <el-card v-if="payPalUrl" class="paypal-link">
      <template #header>
        <div class="card-header">
          <span>支付单号: {{ payPalOrderNo }}</span>
        </div>
      </template>
      <p>点击下方链接前往 PayPal 支付页面:</p>
      <el-link :href="payPalUrl" target="_blank" type="primary">{{ payPalUrl }}</el-link>
    </el-card>

    <el-alert v-if="error" :title="error" type="error" show-icon></el-alert>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { useStore } from 'vuex';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';

const store = useStore();
const route = useRoute();

const formData = reactive({
  uni: route.params.uni || '',
  orderNo: route.params.orderNo || '',
  payType: 'paypal',
  payChannel: 'PC',
});

const loading = ref(false);
const paypalForm = ref(null);

const payPalUrl = computed(() => store.getters['createPayPalOrder/getPayPalUrl']);
const payPalOrderNo = computed(() => store.getters['createPayPalOrder/getPayPalOrderNo']);
const error = computed(() => store.getters['createPayPalOrder/getError']);

const rules = {
  uni: [{ required: true, message: '请输入唯一标识', trigger: 'blur' }],
  orderNo: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
};

const createPayPalOrder = async () => {
  try {
    await paypalForm.value.validate();
    loading.value = true;

    const result = await store.dispatch('createPayPalOrder/createPayPalOrder', formData);

    if (!result.success) {
      ElMessage.error(result.error || '生成支付单号失败');
    }
  } catch (err) {
    console.error('生成支付单号失败:', err);
    ElMessage.error(err.message || '生成支付单号失败，请稍后再试');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.paypal-payment {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.paypal-link {
  margin-top: 20px;
}

.el-alert {
  margin-top: 20px;
}
</style>
